/**
 * Classname : SchedulerThread.java
 *
 * Version information: 1.0
 *
 * Date: Mar 09, 2012 Bui.Trung.Dung create
 *
 */
package com.history.scheduler;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.history.business.ArticleManager;
import com.history.common.Logit;
import com.history.common.SpringContextFactory;
import com.history.common.file.FileProcess;
import com.history.domain.bean.Article;

/**
 * @author Bui.Trung.Dung
 * 
 */
public class SchedulerThread {
	
	private static Logit log = Logit.getInstance(SchedulerThread.class);

	private long _waitInternal = 2000; // millisecond

	private Timer _timer = null;

	private TimerTask _task = null;

	private boolean taskDone = false;
	
	public static int countThread = 0;

	public SchedulerThread() {
		try{
			
			this._waitInternal = 2000;
			this._task = new SynchronizeArticle();
			this._timer = new Timer();
			
			this._timer.schedule(_task, 0, _waitInternal);
		}catch (Throwable e) {
			log.error("Error in initializing scheduler Thread.");
			log.error(e.getMessage(), e);
		}
	}
	
	/**
	 * @author Bui.Trung.Dung
	 */
	class SynchronizeArticle extends TimerTask {
		public void run() {			
			taskDone = false;
			try {
				List<String> list = FileProcess.read();
				System.out.println("list article " + list.size());
				ArticleManager articleManager 		= null;
				ArticleManager articleManagerLocal 	= null;
				if (list != null && list.size() > 0) {
					try {
						articleManager 		= SpringContextFactory.getArticleManager(true);
						articleManagerLocal = SpringContextFactory.getArticleManager(false);
						// Check the network is OK or not?
						if (articleManager != null && articleManagerLocal != null) {
							for (String str : list) {
								String[] arr = str.split(",");
								
								// Get from local
								Article article = articleManagerLocal.findById(arr[0]);
								
								// Insert into administrator database
								articleManager.updateArticle(article);
							}
							// Clear text file
							FileProcess.move();
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}				
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			taskDone = true;
		}
	}

	/**
	 * check s if scheduler is in RUN() method  or Not
	 * @return
	 */
	public boolean returnStatus() {
		return taskDone;
	}

	/**
	 * close the task of scheduler
	 */
	public void close() {
		this._task.cancel();
	}
}
